<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta
            name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    >
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>列表anmi</title>
    <style>
        .delay-trans {
            transition: 0.1s all;
        }
        .anmi-list > li {
            margin: 5px 10px;
            cursor: pointer;
            /*user-select: none;*/
        }
        .anmi-list > li:hover {
            background: azure;
        }
        
    </style>
</head>
<body>
<h1>todo list</h1>
<button id="sort">逆序</button>
<input type="text" id="userInput"/>
<ul class="anmi-list"></ul>
<script>
    const ul = document.querySelector(".anmi-list");
    const btn = document.querySelector("#sort");
    const input = document.querySelector("#userInput");
    function createListItem(text){
        const liItem = document.createElement("li");
        liItem.textContent = text;
        return liItem;
    }
    function render(listData){
        const frag = document.createDocumentFragment();
        for (const text of listData) {
            frag.appendChild(createListItem(text));
        }
        while(ul.hasChildNodes()) {
            ul.removeChild(ul.firstChild);
        }
        ul.appendChild(frag);
    }
    function swapElements(el1, el2){
        const fe = el1.nextSibling;
        const le = el2.previousSibling;
        ul.insertBefore(el2, fe);
        ul.insertBefore(el1, le.nextSibling);

        const frect = el1.getBoundingClientRect();
        const lrect = el2.getBoundingClientRect();

        el1.style.translate = `0 ${lrect.top - frect.top}px`;
        el2.style.translate = `0 ${frect.top - lrect.top}px`;

        el1.classList.remove("delay-trans");
        el2.classList.remove("delay-trans");

        requestAnimationFrame(() => {
            el1.classList.add("delay-trans");
            el2.classList.add("delay-trans");

            el1.style.translate = `0 0`;
            el2.style.translate = `0 0`;
        });
    }
    const data = ["dpfhap", "df;hnadop", "hahahaha"];
    render(data);
    btn.addEventListener("click", function () {
        const lis = ul.childNodes;
        // swapElements(lis[0], lis[data.length - 1]);
        for (let i = 0; i < (lis.length - 1) / 2; i++) {
            swapElements(lis[i], lis[data.length - 1 - i]);
        }
    });
    input.addEventListener("keydown", (e) => {
       if (e.key === "Enter" && e.target.value) {
           data.push(e.target.value);
           render(data);
       }
    });
</script>
</body>
</html>